﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.YunZhiJia;
using Kingdee.BOS.Core.ChartConfig;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 物料审核插件
    /// </summary>
    /// <remarks>
    /// 功能：物料在集团创建审核后自动传到CRM。
    /// 创建人：wzx
    /// 创建日期：2024.1.8
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    [Description("物料审核同步至CRM")]
    [HotUpdate]
    public class MaterialToCRM : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            //存货类别
            e.FieldKeys.Add("FCategoryID");
            //物料编码
            e.FieldKeys.Add("FNumber");
            //物料名称
            e.FieldKeys.Add("FName");
            //物料分组
            e.FieldKeys.Add("FMaterialGroup");
            //规格型号
            e.FieldKeys.Add("FSpecification");
            //描述
            e.FieldKeys.Add("FDescription");
            //物料属性
            e.FieldKeys.Add("FErpClsID");


            //基本单位
            e.FieldKeys.Add("FBaseUnitId");
            //库存单位
            e.FieldKeys.Add("FStoreUnitID");

            //保质期
            e.FieldKeys.Add("FEXPPERIOD");

            //启用批号管理
            e.FieldKeys.Add("FISBATCHMANAGE");
            //启用库存管理
            e.FieldKeys.Add("FISSNMANAGE");

            //使用组织
            e.FieldKeys.Add("FUseOrgId");

            //同步CRM状态
            e.FieldKeys.Add("F_DEV_FSTATUS");
            //默认税率
            e.FieldKeys.Add("FTaxRateId");
            //税收分类
            e.FieldKeys.Add("FTaxCategoryCodeId");
            //销售单位
            e.FieldKeys.Add("FSaleUnitId");
            //销售单位换算率分子
            e.FieldKeys.Add("FSaleURNum");
            //销售单位换算率分母
            e.FieldKeys.Add("FSaleURNom");
            //销售计价单位
            e.FieldKeys.Add("FSalePriceUnitId");
            //销售计价单位换算率分子
            e.FieldKeys.Add("FSalePriceURNum");
            //销售计价单位换算率分母
            e.FieldKeys.Add("FSalePriceURNom");
            //产品经理
            e.FieldKeys.Add("F_SVZW_Assistant_qtr_apv");
            //创建组织 
            e.FieldKeys.Add("FCreateOrgId");
            //禁用人 
            e.FieldKeys.Add("FForbidderId");
            //禁用日期 
            e.FieldKeys.Add("FForbidDate");
            //禁用状态 
            e.FieldKeys.Add("FForbidStatus");
            //制造策略 
            e.FieldKeys.Add("FMfgPolicyId");
            //加工 
            e.FieldKeys.Add("F_SVZW_Text_qtr");
            //包材 
            e.FieldKeys.Add("F_SVZW_Text_qtr_83g");
            //包装型号 
            e.FieldKeys.Add("F_SVZW_Text_qtr_83g_re5");
            //商品名 
            e.FieldKeys.Add("F_SVZW_Text_qtr_83g_w5c1");
            //含量
            e.FieldKeys.Add("F_SVZW_Text_qtr_83g_uky");
            //成品颜色
            e.FieldKeys.Add("F_SVZW_Text_qtr_83g_tzk");
            //有效成分
            e.FieldKeys.Add("F_SVZW_Text_qtr_83g_ca9");
            //渠道品牌
            e.FieldKeys.Add("F_SVZW_Text_qtr_83g_h1g");
            //是否定制
            e.FieldKeys.Add("F_RDLV_Combo_qtr1");
            //最小包装
            e.FieldKeys.Add("F_SVZW_Text_qtr_83g_dvn");
            //产品性质
            e.FieldKeys.Add("F_SVZW_Combo_yrr");
            //产品登记证
            e.FieldKeys.Add("F_RDLV_Assistant_ca9");
            //登记号到期日期
            e.FieldKeys.Add("F_SVZW_DateTime_43c");
            //生产批准证号
            e.FieldKeys.Add("F_SVZW_Text_zc5_ne1");
            //批准证到期日期
            e.FieldKeys.Add("F_SVZW_DateTime_43c_6oq");
            //标准证号
            e.FieldKeys.Add("F_SVZW_Text_zc5_ne1_pzg");
            //标准证到期日期
            e.FieldKeys.Add("F_SVZW_DateTime_43c_9uj");
            //产品品类
            e.FieldKeys.Add("F_SVZW_Assistant_qtr");
            //产品类别
            e.FieldKeys.Add("F_SVZW_Assistant_83g");
            //包材类型
            e.FieldKeys.Add("F_SVZW_Assistant_qtr_re5");
            //淡储类型
            e.FieldKeys.Add("F_SVZW_Assistant_qtr_tzk");
            //剂型
            e.FieldKeys.Add("F_SVZW_Assistant_qtr_ca9");
            //商标名称
            e.FieldKeys.Add("F_SVZW_Assistant_qtr_uky");
            //生产类型
            e.FieldKeys.Add("F_SVZW_Assistant_qtr_dvn");
            //开票名称
            e.FieldKeys.Add("F_RDLV_Text_1xj");
            //开票单位
            e.FieldKeys.Add("F_RDLV_Base_3iy");
            //开票规格型号
            e.FieldKeys.Add("F_RDLV_Text_k79");


            //单件销售单位数量
            e.FieldKeys.Add("F_QLTK_Qty_qtr");
            //创建人
            e.FieldKeys.Add("FCreatorId");
            //默认使用组织
            e.FieldKeys.Add("F_QLTK_Base_qtr2");


        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            int successNum = 0;//记录成功数
            base.AfterExecuteOperationTransaction(e);
            string InvokeType = "";
            if (this.FormOperation.Operation.ToUpper() == "AUDIT")
            {
                InvokeType = "物料审核自动上传CRM";
            }
            else if (this.FormOperation.Operation.ToUpper() == "REUPLOADMATERIAL")
            {
                InvokeType = "物料手工上传CRM";
            }
            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (DynamicObject entity in e.DataEntitys)
            {
                string UserAccount = "";//用户账号
                DynamicObject User = entity["CreatorId"] as DynamicObject;//用户
                if (User!=null)
                {
                    UserAccount = Convert.ToString(User["UserAccount"]);
                }
                
                string FID = Convert.ToString(entity["Id"]);//物料内码                      
                string Number = entity["Number"].ToString();//物料编码      
                string Name = entity["Name"].ToString();//物料名称

                DynamicObject CreateOrg = entity["CreateOrgId"] as DynamicObject;//创建组织
                string CreateOrgId = "";//创建组织内码
                string CreateOrgNo = "";//创建组织编码
                string CreateOrgName = "";
                if (CreateOrg != null)
                {
                    CreateOrgId = Convert.ToString(CreateOrg["ID"]);//创建组织内码
                    CreateOrgNo = Convert.ToString(CreateOrg["Number"]);//创建组织编码
                    CreateOrgName = Convert.ToString(CreateOrg["Name"]);//创建组织名称
                }

                DynamicObject DefaultUserOrg = entity["F_QLTK_Base_qtr2"] as DynamicObject;//默认使用组织
                string DefaultUserOrgId = "";//默认使用组织内码
                string DefaultUserOrgNo = "";//默认使用组织编码
                string DefaultUserOrgName = "";
                if (DefaultUserOrg != null)
                {
                    DefaultUserOrgId = Convert.ToString(DefaultUserOrg["ID"]);//  默认使用组织内码
                    DefaultUserOrgNo = Convert.ToString(DefaultUserOrg["Number"]);//默认使用组织编码
                    DefaultUserOrgName = Convert.ToString(DefaultUserOrg["Name"]);//默认使用组织名称
                }




                DynamicObject UseOrg = entity["UseOrgId"] as DynamicObject;//使用组织
                string UseOrgId = "";//使用组织内码
                string UseOrgNo = "";//使用组织编码
                string UseOrgName = "";
                if (UseOrg != null)
                {
                    UseOrgId = Convert.ToString(UseOrg["ID"]);//使用组织内码
                    UseOrgNo = Convert.ToString(UseOrg["Number"]);//使用组织编码
                    UseOrgName = Convert.ToString(UseOrg["Name"]);//组织名称
                }
                string UseOrgNumber = "";
                string sql_material = string.Format(@"select FUseOrgId 
from T_BD_MATERIAL where FNUMBER='{0}' and FDocumentStatus='C' and FForbidStatus='A'", Number);
                DataTable dt_material = DBUtils.ExecuteDataSet(this.Context, sql_material).Tables[0];
                if (dt_material.Rows.Count > 0)
                {
                    foreach (DataRow item in dt_material.Rows)
                    {
                        string sql_MO = string.Format(@"select FNUMBER from CRM_V_ProductionBase where FID='{0}'", Convert.ToString(dt_material.Rows[dt_material.Rows.IndexOf(item)]["FUseOrgId"]));
                        DataTable dt_MO = DBUtils.ExecuteDataSet(this.Context, sql_MO).Tables[0];
                        if (dt_MO.Rows.Count > 0)
                        {
                            UseOrgNumber = UseOrgNumber + "," + Convert.ToString(dt_MO.Rows[0]["FNUMBER"]);
                        }
                    }

                }
                if (UseOrgNumber != "" && UseOrgNumber != null)
                {
                    UseOrgNumber = UseOrgNumber.Substring(1, UseOrgNumber.Length - 1);
                }



                string FSTATUS = Convert.ToString(entity["F_DEV_FSTATUS"]);//同步CRM状态 空-未同步，成功-同步成功，失败-同步失败

                string FDescription = entity["Description"].ToString();//描述
                string Specification = entity["Specification"].ToString();//规格型号
                string strMateGroupNo = string.Empty;//传递给SRM的物料分组编码
                DynamicObject MaterialGroup = entity["MaterialGroup"] as DynamicObject;//物料分组
                string MaterialGroupNo = "";//物料分组编码
                string MaterialGroupID = "";//物料分组内码
                string MaterialGroupName = "";//物料分组名称
                string MaterialParentGroupID = null;//物料分组父级内码
                string MaterialParentGroupNumber = "";//物料分组父级编码
                string MaterialGroupDescription = "";//物料分组描述
                if (MaterialGroup != null)
                {
                    MaterialGroupNo = Convert.ToString(MaterialGroup["Number"]);//物料分组编码
                    MaterialGroupID = MaterialGroup["ID"].ToString();//物料分组内码
                    MaterialGroupName = MaterialGroup["Name"].ToString();//物料分组名称

                    string strSgl = "SELECT FNUMBER,FPARENTID FROM T_BD_MATERIALGROUP WHERE FID = '" + MaterialGroupID + "' ";
                    DataTable dtSgl = DBUtils.ExecuteDataSet(this.Context, strSgl).Tables[0];
                    if (dtSgl.Rows.Count > 0)
                    {
                        MaterialParentGroupID = dtSgl.Rows[0]["FPARENTID"].ToString();//父级分组内码
                        if (MaterialParentGroupID != "0")//存在父级分组
                        {
                            string strSglP = "SELECT FNUMBER FROM T_BD_MATERIALGROUP WHERE FID = '" + MaterialParentGroupID + "' ";
                            DataTable dtSglP = DBUtils.ExecuteDataSet(this.Context, strSglP).Tables[0];
                            MaterialParentGroupNumber = dtSglP.Rows[0]["FNUMBER"].ToString();//父级分组编码
                        }
                    }
                    string strSglGroupL = "SELECT FDESCRIPTION FROM T_BD_MATERIALGROUP_L WHERE FID = '" + MaterialGroupID + "' and FLOCALEID=2052";
                    DataTable dtSglGroupL = DBUtils.ExecuteDataSet(this.Context, strSglGroupL).Tables[0];
                    if (dtSglGroupL.Rows.Count > 0)
                    {
                        MaterialGroupDescription = dtSglGroupL.Rows[0]["FDESCRIPTION"].ToString();//物料分组描述
                    }
                }
                #region 基本信息
                var MaterialBase = entity["MaterialBase"] as DynamicObjectCollection;//基本信息

                string BaseUnitId = "";//基本单位内码 
                string BaseUnitNo = "";//基本单位编码
                string BaseUnitName = "";//基本单位名称
                string materialTypeName = "";//物料属性对应枚举值名称
                string TaxRateNumber = "";//默认税率
                int TaxRate = 0;//税率
                string TaxCategoryCodeNumber = "";//税收分类编码
                string TaxCategoryCodeName = "";//税收分类名称
                string CategoryNo = "";
                if (MaterialBase != null && MaterialBase.Count > 0)
                {
                    var materialType = MaterialBase[0]["ErpClsID"].ToString();//物料属性

                    string sqlErpClsID = @"/*dialect*/ select FCAPTION from T_META_FORMENUMITEM_L a
 inner join T_META_FORMENUMITEM b on a.FENUMID=b.FENUMID
 inner join T_meta_formenum d on b.FID=d.FID
  inner join T_META_FORMENUM_L c on c.FID=d.FID
 where c.FNAME='BD_物料属性' and b.FVALUE='" + materialType + "'";
                    DataTable dtErpClsID = DBUtils.ExecuteDataSet(this.Context, sqlErpClsID).Tables[0];
                    if (dtErpClsID.Rows.Count > 0)
                    {
                        materialTypeName = dtErpClsID.Rows[0]["FCAPTION"].ToString();
                    }
                    DynamicObject BaseUnit = MaterialBase[0]["BaseUnitId"] as DynamicObject;//基本单位
                    if (BaseUnit != null)
                    {
                        BaseUnitId = BaseUnit["ID"].ToString();//基本单位内码 
                        BaseUnitNo = BaseUnit["Number"].ToString();//基本单位编码
                        BaseUnitName = BaseUnit["Name"].ToString();//基本单位名称
                    }

                    //查询集团组织下该物料的税率
                    string sqlTax =string.Format(@"/*dialect*/ select FTaxRateId,c.FNUMBER,FTAXRATE from T_BD_MATERIAL a
 inner join t_BD_MaterialBase b on a.FMATERIALID=b.FMATERIALID
 inner join T_BD_TAXRATE c on b.FTaxRateId=c.FID
 where a.FUSEORGID=1 and a.FNUMBER='{0}'", Number);
                    DataTable dtTax = DBUtils.ExecuteDataSet(this.Context, sqlTax).Tables[0];

                    if (dtTax.Rows.Count>0)
                    {
                        TaxRateNumber = Convert.ToString(dtTax.Rows[0]["FNUMBER"]);
                        TaxRate = Convert.ToInt32(dtTax.Rows[0]["FTAXRATE"]);
                    }
                    //DynamicObject FTaxRate = MaterialBase[0]["TaxRateId"] as DynamicObject;//默认税率
                    //if (FTaxRate != null)
                    //{
                    //    TaxRateNumber = FTaxRate["Number"].ToString();//默认税率编码  
                    //    TaxRate =Convert.ToInt32(FTaxRate["TaxRate"]);//税率
                    //}
                    
                    ////%号后增加25
                    //int index= TaxTypeName.IndexOf("%");
                    //if (index>=0)
                    //{
                    //    TaxTypeName = TaxTypeName.Insert(index+1, "25");
                    //}

                    DynamicObject Category = MaterialBase[0]["CategoryID"] as DynamicObject;//存货类别

                    if (Category != null)
                    {
                        CategoryNo = Convert.ToString(Category["Number"]);
                    }
                }
                #endregion


                #region 库存信息
                var MaterialStock = entity["MaterialStock"] as DynamicObjectCollection;//库存信息
                string FEXPPERIOD = ""; //保质期
                string FISBATCHMANAGE = ""; //启用批号管理
                string FISSNMANAGE = "";
                string StoreUnitNumber = "";//库存单位编码
                if (MaterialStock != null && MaterialStock.Count > 0)
                {
                    FEXPPERIOD = MaterialStock[0]["EXPPERIOD"].ToString(); //保质期
                    FISBATCHMANAGE = MaterialStock[0]["ISBATCHMANAGE"].ToString(); //启用批号管理
                    FISSNMANAGE = MaterialStock[0]["ISSNMANAGE"].ToString(); //启用库存管理
                    DynamicObject StoreUnit = MaterialStock[0]["StoreUnitID"] as DynamicObject;//库存单位
                    if (StoreUnit != null)
                    {
                        StoreUnitNumber = StoreUnit["Number"].ToString();//库存单位编码                            
                    }
                }

                bool ISBATCHMANAGE;//是否启用批号管理
                if (FISBATCHMANAGE.ToUpper() == "TRUE")
                {
                    ISBATCHMANAGE = true;
                }
                else
                {
                    ISBATCHMANAGE = false;
                }

                bool ISSNMANAGE;//是否启用库存管理
                if (FISSNMANAGE.ToUpper() == "TRUE")
                {
                    ISSNMANAGE = true;
                }
                else
                {
                    ISSNMANAGE = false;
                }
                #endregion


                #region 销售信息
                var MaterialSale = entity["MaterialSale"] as DynamicObjectCollection;//销售信息
                string SaleUnitNumber = "";//销售单位
                string xsdwhssl = "";//销售单位换算量
                string SalePriceUnitNumber = "";//销售计价单位
                string xsjjdwhssl = "";//销售计价单位换算量
                if (MaterialSale != null && MaterialSale.Count > 0)
                {
                    DynamicObject SaleUnit = MaterialSale[0]["SaleUnitId"] as DynamicObject;//销售单位
                    if (SaleUnit != null)
                    {
                        SaleUnitNumber = SaleUnit["Number"].ToString();//销售单位编码                            
                    }
                    xsdwhssl = ((decimal)MaterialSale[0]["SaleURNum"] / (decimal)MaterialSale[0]["SaleURNom"]).ToString();
                    DynamicObject TaxCategoryCode = MaterialSale[0]["TaxCategoryCodeId"] as DynamicObject;//税收分类
                    if (TaxCategoryCode != null)
                    {
                        TaxCategoryCodeNumber = TaxCategoryCode["Number"].ToString();// 税收分类编码
                        TaxCategoryCodeName = TaxCategoryCode["Name"].ToString();//税收分类名称
                    }
                    DynamicObject SalePriceUnit = MaterialSale[0]["SalePriceUnitId"] as DynamicObject;//销售计价单位
                    if (SalePriceUnit != null)
                    {
                        SalePriceUnitNumber = SalePriceUnit["Number"].ToString();//销售计价单位编码                            
                    }
                    xsjjdwhssl = ((decimal)MaterialSale[0]["SalePriceURNum"] / (decimal)MaterialSale[0]["SalePriceURNom"]).ToString();
                }
                #endregion


                #region 计划信息
                var MaterialPlan = entity["MaterialPlan"] as DynamicObjectCollection;//计划信息
                string MfgPolicyNumber = "";//制造策略
                if (MaterialPlan != null && MaterialPlan.Count > 0)
                {
                    DynamicObject MfgPolicy = MaterialPlan[0]["MfgPolicyId"] as DynamicObject;//销售单位
                    if (MfgPolicy != null)
                    {
                        MfgPolicyNumber = MfgPolicy["Number"].ToString();//制造策略编码                            
                    }
                }
                #endregion




                string cpjlName = "";//产品经理名称
                DynamicObject cpjl = entity["F_SVZW_Assistant_qtr_apv"] as DynamicObject;//产品经理
                if (cpjl != null)
                {
                    cpjlName = cpjl["FNUMBER"].ToString();
                }
                int ForbidderId = 0;//禁用人
                string ForbidDate = "";//禁用日期
                string ForbidStatus = "";//禁用状态
                DynamicObject Forbidde = entity["ForbidderId"] as DynamicObject;//禁用人
                if (Forbidde != null)
                {
                    ForbidderId = Convert.ToInt32(Forbidde["Id"]);
                }
                ForbidDate = Convert.ToString(entity["ForbidDate"]);
                ForbidStatus = entity["ForbidStatus"].ToString();

                #region 物料属性
                string jg = entity["F_SVZW_Text_qtr"].ToString();//加工
                string bc = entity["F_SVZW_Text_qtr_83g"].ToString();//包材
                string bzxh = entity["F_SVZW_Text_qtr_83g_re5"].ToString();//包装型号
                string spm = entity["F_SVZW_Text_qtr_83g_w5c1"].ToString();//商品名
                string hl = entity["F_SVZW_Text_qtr_83g_uky"].ToString();//含量
                string cpys = entity["F_SVZW_Text_qtr_83g_tzk"].ToString();//成品颜色
                string yxcf = entity["F_SVZW_Text_qtr_83g_ca9"].ToString();//有效成分
                string qdpp = entity["F_SVZW_Text_qtr_83g_h1g"].ToString();//渠道品牌
                string dz = entity["F_RDLV_Combo_qtr1"].ToString();//定制
                string zxbz = entity["F_SVZW_Text_qtr_83g_dvn"].ToString();//最小包装
                string cpxz = entity["F_SVZW_Combo_yrr"].ToString();//产品性质
                string cpdjzh = "";
                DynamicObject Assistant = entity["F_RDLV_Assistant_ca9"] as DynamicObject;
                if (Assistant != null)
                {
                    cpdjzh = Convert.ToString(Assistant["FNUMBER"]);//产品登记证
                }

                string djhdqrq = Convert.ToString(entity["F_SVZW_DateTime_43c"]);//登记号到期日期
                string scpzzh = entity["F_SVZW_Text_zc5_ne1"].ToString();//生产批准证号
                string pzzdqrq = Convert.ToString(entity["F_SVZW_DateTime_43c_6oq"]);//批准证到期日期
                string bzzh = entity["F_SVZW_Text_zc5_ne1_pzg"].ToString();//标准证号
                string bzzdqrq = Convert.ToString(entity["F_SVZW_DateTime_43c_9uj"]);//标准证到期日期

                DynamicObject cppl = entity["F_SVZW_Assistant_qtr"] as DynamicObject;//产品品类
                string cpplName = "";//产品品类名称
                if (cppl != null)
                {
                    cpplName = cppl["FNUMBER"].ToString();
                }
                DynamicObject cplb = entity["F_SVZW_Assistant_83g"] as DynamicObject;//产品类别
                string cplbName = "";//产品类别名称
                if (cplb != null)
                {
                    cplbName = cplb["FNUMBER"].ToString();
                }
                DynamicObject bclx = entity["F_SVZW_Assistant_qtr_re5"] as DynamicObject;//包材类型
                string bclxName = "";//包材类型名称
                if (bclx != null)
                {
                    bclxName = bclx["FNUMBER"].ToString();
                }
                DynamicObject dclx = entity["F_SVZW_Assistant_qtr_tzk"] as DynamicObject;//淡储类型
                string dclxName = "";//淡储类型名称
                if (dclx != null)
                {
                    dclxName = dclx["FNUMBER"].ToString();
                }
                DynamicObject jx = entity["F_SVZW_Assistant_qtr_ca9"] as DynamicObject;//剂型
                string jxName = "";//剂型名称
                if (jx != null)
                {
                    jxName = jx["FNUMBER"].ToString();
                }
                DynamicObject sb = entity["F_SVZW_Assistant_qtr_uky"] as DynamicObject;//商标
                string sbName = "";//商标名称
                if (sb != null)
                {
                    sbName = sb["FNUMBER"].ToString();
                }
                DynamicObject sclx = entity["F_SVZW_Assistant_qtr_dvn"] as DynamicObject;//生产类型
                string sclxName = "";//生产类型名称
                if (sclx != null)
                {
                    sclxName = sclx["FNUMBER"].ToString();
                }
                
                string InvoicingName = entity["F_RDLV_Text_1xj"].ToString();//开票名称
                string InvoiceSpec = Convert.ToString(entity["F_RDLV_Text_k79"]);//开票规格型号

                DynamicObject InvoicingUnit = entity["F_RDLV_Base_3iy"] as DynamicObject;//开票单位
                string InvoicingUnitNo = "";//开票单位编码
                if (InvoicingUnit != null)
                {
                    InvoicingUnitNo = InvoicingUnit["NUMBER"].ToString();
                }

                #endregion

                string SglMateAvailableDept = string.Format(@"/*dialect*/select b.FNUMBER from QLTK_t_MateAvailableDept a
inner join T_BD_DEPARTMENT b on a.F_QLTK_DEPARTMENT=b.FDEPTID
where a.FMATERIALID= '{0}'", FID);

              
                DataTable dtMateAvailableDept = DBUtils.ExecuteDataSet(this.Context, SglMateAvailableDept).Tables[0];
                string MateAvailableDept = "";//可用部门
                if (dtMateAvailableDept.Rows.Count > 0)
                {
                    foreach (DataRow item in dtMateAvailableDept.Rows)
                    {
                        if (item.Table.Rows.IndexOf(item) ==0)
                        {
                            MateAvailableDept= item["FNUMBER"].ToString();
                        }
                        else
                        {
                            MateAvailableDept = MateAvailableDept + "," + item["FNUMBER"].ToString();
                        }
                    }
                    
                }

                decimal PieceConversion = 0;//单件销售单位数量
                PieceConversion = Convert.ToDecimal(entity["F_QLTK_Qty_qtr"]);
                

                if (CategoryNo == "CHLB05_SYS"|| CategoryNo == "1405"|| CategoryNo == "1403.02")
                {
                    #region 物料mainTable数组
                    MaterialModel.materialList mainTable = new MaterialModel.materialList();
                    mainTable.name = Name;
                    mainTable.code = Number;
                    mainTable.category = MaterialGroupNo;
                    mainTable.ggxh = Specification;
                    mainTable.jbdw = BaseUnitNo;
                    mainTable.mrsl = TaxRateNumber;
                    mainTable.sflbm = TaxCategoryCodeNumber;
                    mainTable.sflmc = TaxCategoryCodeName;
                    mainTable.kcdw = StoreUnitNumber;
                    mainTable.xsdw = SalePriceUnitNumber;
                    mainTable.dwhssl = xsjjdwhssl;
                    mainTable.cpjl = cpjlName;
                    mainTable.yxq = null;
                    mainTable.scrq = null;
                    mainTable.szxx = null;
                    mainTable.cjzz = CreateOrgNo;
                    mainTable.syzz = null;
                    mainTable.jyr = 0;
                    mainTable.jyrq = null;
                    if (ForbidStatus=="B")
                    {
                        mainTable.jyzt = "0";
                    }
                    else
                    {
                        mainTable.jyzt = "1";
                    }
                    
                    mainTable.tgf = null;
                    mainTable.zzcl = MfgPolicyNumber;
                    mainTable.mrzz = UseOrgNo;
                    mainTable.jg = jg;
                    mainTable.bc = bc;
                    mainTable.bzxh = bzxh;
                    mainTable.spm = spm;
                    mainTable.hl = hl;
                    mainTable.cpys = cpys;
                    mainTable.yxcf = yxcf;
                    mainTable.qdpp = qdpp;
                    if (dz=="0")
                    {
                        mainTable.dz = "否";
                    }
                    else if (dz=="1")
                    {
                        mainTable.dz = "是";
                    }
                    
                    mainTable.zxbz = zxbz;
                    mainTable.cpxz = cpxz;
                    mainTable.cpdjzh = cpdjzh;
                    mainTable.djhdqrq = djhdqrq;
                    mainTable.scpzzh = scpzzh;
                    mainTable.pzzdqrq = pzzdqrq;
                    mainTable.bzzh = bzzh;
                    mainTable.bzzdqrq = bzzdqrq;
                    mainTable.cppl = cpplName;
                    mainTable.cplb = cplbName;
                    mainTable.bclx = bclxName;
                    mainTable.dclx = dclxName;
                    mainTable.jx = jxName;
                    mainTable.sbmc = sbName;
                    mainTable.sclx = sclxName;
                    mainTable.erpcpnm = FID;
                    mainTable.cpsyzz = UseOrgNumber;
                    mainTable.jjdw = SaleUnitNumber;
                    mainTable.jjdwhssl = xsdwhssl;
                    mainTable.kpmc = InvoicingName;
                    mainTable.kpdw = InvoicingUnitNo;
                    mainTable.kpggxh = InvoiceSpec;
                    mainTable.sl = TaxRate;
                    mainTable.sybm = MateAvailableDept;
                    mainTable.jshs = PieceConversion;

                    mainTable.mrsyzz = DefaultUserOrgNo;
                    #endregion
                    #region 物料分组mainTable数组
                    bool isContinue = true;//是否继续循环 
                    int i = 1;
                    if (MaterialParentGroupID == null || MaterialParentGroupID == "" && MaterialParentGroupID == "0")
                    {
                        isContinue = false;
                    }
                    string TMaterialGroupNo = "";
                    string TMaterialGroupDescription = "";
                    string TMaterialGroupName = "";
                    string TMaterialParentGroupNumber = "";
                    string TMaterialGroupID = "";
                    string TMaterialParentGroupID = "";
                    TMaterialGroupNo = MaterialGroupNo;
                    TMaterialGroupDescription = MaterialGroupDescription;
                    TMaterialGroupName = MaterialGroupName;
                    TMaterialParentGroupNumber = MaterialParentGroupNumber;
                    TMaterialGroupID = MaterialGroupID;
                    TMaterialParentGroupID = MaterialParentGroupID;
                    DBServiceHelper.ExecuteDataSet(this.Context, @"/*dialect*/TRUNCATE TABLE MATERIALGROUPLEVEL");//清空分组中间表
                    if (TMaterialGroupID != null && TMaterialGroupID != "" && TMaterialGroupID != "0")
                    {
                        string SQLinsertGroup = string.Format(@"/*dialect*/insert into MATERIALGROUPLEVEL
values({0},'{1}','{2}','{3}','{4}','{5}','{6}')", i, MaterialGroupNo, MaterialGroupDescription, MaterialGroupName, MaterialParentGroupNumber, MaterialGroupID, MaterialParentGroupID);
                        DBServiceHelper.ExecuteDataSet(this.Context, SQLinsertGroup);
                    }

                    while (isContinue)
                    {
                        i++;
                        //物料分组存在父级分组
                        if (TMaterialParentGroupID != null && TMaterialParentGroupID != "" && TMaterialParentGroupID != "0")
                        {
                            string SQLmaterialGroup = @"/*dialect*/select * from T_BD_MATERIALGROUP where FID='" + TMaterialParentGroupID + "'";
                            DataTable dtmaterialGroup = DBServiceHelper.ExecuteDataSet(this.Context, SQLmaterialGroup).Tables[0];
                            if (dtmaterialGroup != null && dtmaterialGroup.Rows.Count > 0)
                            {
                                string SQLmaterialGroupL = @"/*dialect*/select * from T_BD_MATERIALGROUP_L where FID='" + TMaterialParentGroupID + "' and FLOCALEID=2052";
                                DataTable dtGroupL = DBServiceHelper.ExecuteDataSet(this.Context, SQLmaterialGroupL).Tables[0];

                                TMaterialGroupNo = dtmaterialGroup.Rows[0]["FNUMBER"].ToString();
                                TMaterialGroupDescription = dtGroupL.Rows[0]["FDESCRIPTION"].ToString();
                                TMaterialGroupName = dtGroupL.Rows[0]["FNAME"].ToString();
                                TMaterialGroupID = dtmaterialGroup.Rows[0]["FID"].ToString();
                                TMaterialParentGroupID = dtmaterialGroup.Rows[0]["FPARENTID"].ToString();
                                if (dtmaterialGroup.Rows[0]["FPARENTID"].ToString() != "0" && dtmaterialGroup.Rows[0]["FPARENTID"].ToString() != null)//有父分组
                                {
                                    string SQLmaterialGroupP = @"/*dialect*/select * from T_BD_MATERIALGROUP where FID='" + dtmaterialGroup.Rows[0]["FPARENTID"].ToString() + "' ";
                                    DataTable dtGroupP = DBServiceHelper.ExecuteDataSet(this.Context, SQLmaterialGroupP).Tables[0];
                                    TMaterialParentGroupNumber = dtGroupP.Rows[0]["FNUMBER"].ToString();
                                }
                                else
                                {
                                    TMaterialParentGroupID = null;
                                    TMaterialParentGroupNumber = null;
                                }
                            }
                            string SQLinsertGroupN = string.Format(@"/*dialect*/insert into MATERIALGROUPLEVEL
values({0},'{1}','{2}','{3}','{4}','{5}','{6}')", i, TMaterialGroupNo, TMaterialGroupDescription, TMaterialGroupName, TMaterialParentGroupNumber, TMaterialGroupID, TMaterialParentGroupID);
                            DBServiceHelper.ExecuteDataSet(this.Context, SQLinsertGroupN);
                        }
                        else
                        {
                            isContinue = false;//终止循环
                        }
                    }


                    #endregion
                    string SqlGroupM = string.Format(@"select * from MATERIALGROUPLEVEL order by Level desc");
                    DataTable dtGroupM = DBServiceHelper.ExecuteDataSet(this.Context, SqlGroupM).Tables[0];

                    if (this.FormOperation.Operation.ToUpper() == "AUDIT" || this.FormOperation.Operation.ToUpper() == "REUPLOADMATERIAL")
                    {
                        for (int j = 0; j < dtGroupM.Rows.Count; j++)
                        {
                            string[] paramGroup = new string[6];
                            paramGroup[0] = dtGroupM.Rows[j]["MaterialGroupNo"].ToString();
                            paramGroup[1] = dtGroupM.Rows[j]["MaterialGroupDescription"].ToString();
                            paramGroup[2] = dtGroupM.Rows[j]["MaterialGroupName"].ToString();
                            paramGroup[3] = dtGroupM.Rows[j]["MaterialParentGroupNumber"].ToString();
                            paramGroup[4] = dtGroupM.Rows[j]["MaterialGroupID"].ToString();
                            paramGroup[5] = dtGroupM.Rows[j]["MaterialParentGroupID"].ToString();
                            string Sql = string.Format(@"select * from RDLV_t_CRMInterfaceLog where F_DEV_FINVOKETYPE='新增物料分组'  and F_DEV_FBILLID='" + dtGroupM.Rows[j]["MaterialGroupID"].ToString() + "' order by F_DEV_FDATE desc");
                            DataTable dtGroup = DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];
                            string resultSearch = CRMSearchGroup(dtGroupM.Rows[j]["MaterialGroupNo"].ToString(), UserAccount);
                            if (resultSearch == dtGroupM.Rows[j]["MaterialGroupNo"].ToString())//当前物料分组已同步CRM
                            {
                                Return result1 = CRMUpdateMaterialGroup(paramGroup, UserAccount);
                                if (result1.status == "1")
                                {
                                    #region 物料分组写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = dtGroupM.Rows[j]["MaterialGroupNo"].ToString();
                                    interfaceLog.FBILLID = dtGroupM.Rows[j]["MaterialGroupID"].ToString();
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "更新物料分组";
                                    interfaceLog.FInvokeType = "";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "成功";
                                    interfaceLog.FRequsetData = string.Join(",", paramGroup);
                                    interfaceLog.FReturnData = JsonConvert.SerializeObject(result1.datajson);
                                    interfaceLog.FRequest = string.Join(",", paramGroup);
                                    interfaceLog.FReturn = JsonConvert.SerializeObject(result1.datajson);
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }
                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                    #endregion
                                }
                                else
                                {
                                    #region 物料分组写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = dtGroupM.Rows[j]["MaterialGroupNo"].ToString();
                                    interfaceLog.FBILLID = dtGroupM.Rows[j]["MaterialGroupID"].ToString();
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "更新物料分组";
                                    interfaceLog.FInvokeType = "";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "成功";
                                    interfaceLog.FRequsetData = string.Join(",", paramGroup);
                                    interfaceLog.FReturnData = JsonConvert.SerializeObject(result1.datajson);
                                    interfaceLog.FRequest = string.Join(",", paramGroup);
                                    interfaceLog.FReturn = JsonConvert.SerializeObject(result1.datajson);
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }
                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                    #endregion
                                    IOperationResult operationResult = new OperationResult();
                                    operationResult.OperateResult.Add(new OperateResult()
                                    {
                                        SuccessStatus = false,
                                        Message = string.Format("物料分组更新上传失败，请手工同步！"),
                                        MessageType = MessageType.Warning,
                                        PKValue = 0,
                                    });
                                    this.OperationResult.MergeResult(operationResult);
                                }
                                if (dtGroupM.Rows[j]["Level"].ToString() == "1")//并且最下级分组已同步成功
                                {
                                    string resultMaterialSearch = CRMSearchMATERIAL(Number, UserAccount);
                                    //未同步物料
                                    if (resultMaterialSearch == "无结果")
                                    {
                                        //CRM新增物料接口调用
                                        Return result = CRMAddMATERIAL(mainTable, UserAccount);
                                        if (result.status == "1")
                                        {
                                            #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                            interfaceLog.FBILLNO = Number;
                                            interfaceLog.FBILLID = FID;
                                            interfaceLog.FDATE = System.DateTime.Now;
                                            interfaceLog.FINTERNAME = "新增物料";
                                            interfaceLog.FInvokeType = InvokeType;
                                            interfaceLog.Ftoken = "";
                                            interfaceLog.FSTATUS = "成功";
                                            interfaceLog.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                            interfaceLog.FRequest = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog.FReturn = JsonConvert.SerializeObject(result.datajson);
                                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                            List<string> sqlList = new List<string>();
                                            if (!string.IsNullOrEmpty(LogSql))
                                            {
                                                sqlList.Add(LogSql);
                                            }
                                            //更新单据
                                            string updateSql = string.Format(@"/*dialect*/ update T_BD_MATERIAL set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FMaterialId={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                            sqlList.Add(updateSql);
                                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                            #endregion
                                        }
                                        else
                                        {
                                            #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                            interfaceLog.FBILLNO = Number;
                                            interfaceLog.FBILLID = FID;
                                            interfaceLog.FDATE = System.DateTime.Now;
                                            interfaceLog.FINTERNAME = "新增物料";
                                            interfaceLog.FInvokeType = InvokeType;
                                            interfaceLog.Ftoken = "";
                                            interfaceLog.FSTATUS = "失败";
                                            interfaceLog.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                            interfaceLog.FRequest = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog.FReturn = JsonConvert.SerializeObject(result.datajson);
                                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                            List<string> sqlList = new List<string>();
                                            if (!string.IsNullOrEmpty(LogSql))
                                            {
                                                sqlList.Add(LogSql);
                                            }
                                            //更新单据
                                            string updateSql = string.Format(@"/*dialect*/ update T_BD_MATERIAL set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FMaterialId={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                            sqlList.Add(updateSql);
                                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                            #endregion
                                            IOperationResult operationResult = new OperationResult();
                                            operationResult.OperateResult.Add(new OperateResult()
                                            {
                                                SuccessStatus = false,
                                                Message = string.Format("物料数据上传失败，请手工同步！"),
                                                MessageType = MessageType.Warning,
                                                PKValue = 0,
                                            });
                                            this.OperationResult.MergeResult(operationResult);
                                        }
                                    }
                                    //已同步
                                    else if(resultMaterialSearch== Number)
                                    {
                                        Return result = CRMUpdateMATERIAL(mainTable,  UserAccount);
                                        if (result.status == "1")
                                        {
                                            #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                            interfaceLog.FBILLNO = Number;
                                            interfaceLog.FBILLID = FID;
                                            interfaceLog.FDATE = System.DateTime.Now;
                                            interfaceLog.FINTERNAME = "更新物料";
                                            interfaceLog.FInvokeType = InvokeType;
                                            interfaceLog.Ftoken = "";
                                            interfaceLog.FSTATUS = "成功";
                                            interfaceLog.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                            interfaceLog.FRequest = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog.FReturn = JsonConvert.SerializeObject(result.datajson);
                                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                            List<string> sqlList = new List<string>();
                                            if (!string.IsNullOrEmpty(LogSql))
                                            {
                                                sqlList.Add(LogSql);
                                            }
                                            //更新单据
                                            string updateSql = string.Format(@"/*dialect*/ update T_BD_MATERIAL set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FMaterialId={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                            sqlList.Add(updateSql);
                                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                            #endregion
                                        }
                                        else
                                        {
                                            #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                            interfaceLog.FBILLNO = Number;
                                            interfaceLog.FBILLID = FID;
                                            interfaceLog.FDATE = System.DateTime.Now;
                                            interfaceLog.FINTERNAME = "更新物料";
                                            interfaceLog.FInvokeType = InvokeType;
                                            interfaceLog.Ftoken = "";
                                            interfaceLog.FSTATUS = "失败";
                                            interfaceLog.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                            interfaceLog.FRequest = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog.FReturn = JsonConvert.SerializeObject(result.datajson);
                                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                            List<string> sqlList = new List<string>();
                                            if (!string.IsNullOrEmpty(LogSql))
                                            {
                                                sqlList.Add(LogSql);
                                            }
                                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                            #endregion
                                            IOperationResult operationResult = new OperationResult();
                                            operationResult.OperateResult.Add(new OperateResult()
                                            {
                                                SuccessStatus = false,
                                                Message = string.Format("物料数据更新上传失败，请手工同步！"),
                                                MessageType = MessageType.Warning,
                                                PKValue = 0,
                                            });
                                            this.OperationResult.MergeResult(operationResult);
                                        }
                                    }
                                    else
                                    {
                                        IOperationResult operationResult = new OperationResult();
                                        operationResult.OperateResult.Add(new OperateResult()
                                        {
                                            SuccessStatus = false,
                                            Message = resultMaterialSearch,
                                            MessageType = MessageType.Warning,
                                            PKValue = 0,
                                        });
                                    }
                                }
                            }
                            else if(resultSearch=="无结果")//未同步分组
                            {
                                //CRM新增物料分组接口调用
                                Return result1 = CRMAddMaterialGroup(paramGroup, UserAccount);
                                if (result1.status == "1")
                                {
                                    #region 物料分组写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = dtGroupM.Rows[j]["MaterialGroupNo"].ToString();
                                    interfaceLog.FBILLID = dtGroupM.Rows[j]["MaterialGroupID"].ToString();
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "新增物料分组";
                                    interfaceLog.FInvokeType = "";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "成功";
                                    interfaceLog.FRequsetData = string.Join(",", paramGroup);
                                    interfaceLog.FReturnData = JsonConvert.SerializeObject(result1.datajson);
                                    interfaceLog.FRequest = string.Join(",", paramGroup);
                                    interfaceLog.FReturn = JsonConvert.SerializeObject(result1.datajson);
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }
                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                    #endregion
                                    if (dtGroupM.Rows[j]["Level"].ToString() == "1")
                                    {
                                        //CRM新增物料接口调用
                                        Return result = CRMAddMATERIAL(mainTable, UserAccount);
                                        if (result.status == "1")
                                        {
                                            #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                            Common.InterfaceLog interfaceLog1 = new Common.InterfaceLog();
                                            interfaceLog1.FBILLNO = Number;
                                            interfaceLog1.FBILLID = FID;
                                            interfaceLog1.FDATE = System.DateTime.Now;
                                            interfaceLog1.FINTERNAME = "新增物料";
                                            interfaceLog1.FInvokeType = InvokeType;
                                            interfaceLog1.Ftoken = "";
                                            interfaceLog1.FSTATUS = "成功";
                                            interfaceLog1.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog1.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                            interfaceLog1.FRequest = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog1.FReturn = JsonConvert.SerializeObject(result.datajson);
                                            string LogSql1 = interfaceLog1.WriteCRMLogSql();//获取写入日志单据的SQL
                                            List<string> sqlList1 = new List<string>();
                                            if (!string.IsNullOrEmpty(LogSql1))
                                            {
                                                sqlList1.Add(LogSql1);
                                            }
                                            //更新单据
                                            string updateSql = string.Format(@"/*dialect*/ update T_BD_MATERIAL set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FMaterialId={2}", interfaceLog1.FDATE, interfaceLog1.FSTATUS, FID);
                                            sqlList1.Add(updateSql);
                                            DBServiceHelper.ExecuteBatch(this.Context, sqlList1);
                                            #endregion
                                        }
                                        else
                                        {
                                            #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                            Common.InterfaceLog interfaceLog1 = new Common.InterfaceLog();
                                            interfaceLog1.FBILLNO = Number;
                                            interfaceLog1.FBILLID = FID;
                                            interfaceLog1.FDATE = System.DateTime.Now;
                                            interfaceLog1.FINTERNAME = "新增物料";
                                            interfaceLog1.FInvokeType = InvokeType;
                                            interfaceLog1.Ftoken = "";
                                            interfaceLog1.FSTATUS = "失败";
                                            interfaceLog1.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog1.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                            interfaceLog1.FRequest = JsonConvert.SerializeObject(mainTable);
                                            interfaceLog1.FReturn = JsonConvert.SerializeObject(result.datajson);
                                            string LogSql1 = interfaceLog1.WriteCRMLogSql();//获取写入日志单据的SQL
                                            List<string> sqlList1 = new List<string>();

                                            if (!string.IsNullOrEmpty(LogSql1))
                                            {
                                                sqlList1.Add(LogSql1);
                                            }
                                            //更新单据
                                            string updateSql = string.Format(@"/*dialect*/ update T_BD_MATERIAL set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FMaterialId={2}", interfaceLog1.FDATE, interfaceLog1.FSTATUS, FID);
                                            sqlList1.Add(updateSql);
                                            DBServiceHelper.ExecuteBatch(this.Context, sqlList1);
                                            #endregion
                                            IOperationResult operationResult = new OperationResult();
                                            operationResult.OperateResult.Add(new OperateResult()
                                            {
                                                SuccessStatus = false,
                                                Message = string.Format("物料数据上传失败，请手工同步！"),
                                                MessageType = MessageType.Warning,
                                                PKValue = 0,
                                            });
                                            this.OperationResult.MergeResult(operationResult);
                                        }
                                    }
                                }
                                else
                                {
                                    #region 物料分组写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = dtGroupM.Rows[j]["MaterialGroupNo"].ToString();
                                    interfaceLog.FBILLID = dtGroupM.Rows[j]["MaterialGroupID"].ToString();
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "新增物料分组";
                                    interfaceLog.FInvokeType = "";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "失败";
                                    interfaceLog.FRequsetData = string.Join(",", paramGroup);
                                    interfaceLog.FReturnData = JsonConvert.SerializeObject(result1.datajson);
                                    interfaceLog.FRequest = string.Join(",", paramGroup);
                                    interfaceLog.FReturn = JsonConvert.SerializeObject(result1.datajson);
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }
                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                    #endregion
                                    IOperationResult operationResult = new OperationResult();
                                    operationResult.OperateResult.Add(new OperateResult()
                                    {
                                        SuccessStatus = false,
                                        Message = string.Format("物料数据上传失败，请手工同步！"),
                                        MessageType = MessageType.Warning,
                                        PKValue = 0,
                                    });
                                    this.OperationResult.MergeResult(operationResult);
                                }
                            }
                            else//报错
                            {
                                IOperationResult operationResult = new OperationResult();
                                operationResult.OperateResult.Add(new OperateResult()
                                {
                                    SuccessStatus = false,
                                    Message = resultSearch,
                                    MessageType = MessageType.Warning,
                                    PKValue = 0,
                                });
                            }

                        }
                    }


                    if (this.FormOperation.Operation.ToUpper() == "FORBID")
                    {
                        string resultMaterialSearch = CRMSearchMATERIAL(Number, UserAccount);
                        //未同步物料
                        if (resultMaterialSearch == Number)
                        {
                            mainTable.jyr = ForbidderId;
                            mainTable.jyrq = ForbidDate;
                            mainTable.jyzt = "0";
                            Return result = CRMUpdateMATERIAL(mainTable, UserAccount);
                            if (result.status == "1")
                            {
                                #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = Number;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "更新物料";
                                interfaceLog.FInvokeType = InvokeType;
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "成功";
                                interfaceLog.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                interfaceLog.FRequest = JsonConvert.SerializeObject(mainTable);
                                interfaceLog.FReturn = JsonConvert.SerializeObject(result.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                            }
                            else
                            {
                                #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = Number;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "更新物料";
                                interfaceLog.FInvokeType = InvokeType;
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "失败";
                                interfaceLog.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                interfaceLog.FRequest = JsonConvert.SerializeObject(mainTable);
                                interfaceLog.FReturn = JsonConvert.SerializeObject(result.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                                IOperationResult operationResult = new OperationResult();
                                operationResult.OperateResult.Add(new OperateResult()
                                {
                                    SuccessStatus = false,
                                    Message = string.Format("物料数据更新上传失败，请手工同步！"),
                                    MessageType = MessageType.Warning,
                                    PKValue = 0,
                                });
                                this.OperationResult.MergeResult(operationResult);
                            }
                        }

                    }
                    else if (this.FormOperation.Operation.ToUpper() == "ENABLE")
                    {
                        string resultMaterialSearch = CRMSearchMATERIAL(Number, UserAccount);
                        //同步物料
                        if (resultMaterialSearch == Number)
                        {
                            mainTable.jyr = 0;
                            mainTable.jyrq = null;
                            mainTable.jyzt = "1";
                            Return result = CRMUpdateMATERIAL(mainTable, UserAccount);
                            if (result.status == "1")
                            {
                                #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = Number;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "更新物料";
                                interfaceLog.FInvokeType = InvokeType;
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "成功";
                                interfaceLog.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                interfaceLog.FRequest = JsonConvert.SerializeObject(mainTable);
                                interfaceLog.FReturn = JsonConvert.SerializeObject(result.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                            }
                            else
                            {
                                #region 写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = Number;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "更新物料";
                                interfaceLog.FInvokeType = InvokeType;
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "失败";
                                interfaceLog.FRequsetData = JsonConvert.SerializeObject(mainTable);
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(result.datajson);
                                interfaceLog.FRequest = JsonConvert.SerializeObject(mainTable);
                                interfaceLog.FReturn = JsonConvert.SerializeObject(result.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                                IOperationResult operationResult = new OperationResult();
                                operationResult.OperateResult.Add(new OperateResult()
                                {
                                    SuccessStatus = false,
                                    Message = string.Format("物料数据更新上传失败，请手工同步！"),
                                    MessageType = MessageType.Warning,
                                    PKValue = 0,
                                });
                                this.OperationResult.MergeResult(operationResult);
                            }
                        }


                    }
                }



            }

        }

        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting(string InterfaceName)
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface where F_RDLV_InterfaceName='{0}'", InterfaceName);
            return DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];
        }


        /// <summary>
        /// CRM新增物料接口
        /// </summary>
        public Return CRMAddMATERIAL(MaterialModel.materialList mainTable,string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/create_material";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("新增物料");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToPushNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable, UserAccount);


            return result;
        }

        /// <summary>
        /// CRM更新物料接口
        /// </summary>
        public Return CRMUpdateMATERIAL(MaterialModel.materialList mainTable, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/update_material";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";

            DataTable dt = APISetting("更新物料");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToUpdateNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable,UserAccount);


            return result;
        }

        /// <summary>
        /// CRM新增物料分组接口
        /// </summary>
        public Return CRMAddMaterialGroup(string[] args, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/create_marerial_group";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";

            DataTable dt = APISetting("新增物料分组");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }

            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToPushGroupNews(requestUri1, systemid, currentTimeTamp, md5OfStr, args,UserAccount);


            return result;
        }

        /// <summary>
        /// CRM更新物料分组接口
        /// </summary>
        public Return CRMUpdateMaterialGroup(string[] args, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/update_material_group";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";

            DataTable dt = APISetting("更新物料分组");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }

            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToUpdateGroupNews(requestUri1, systemid, currentTimeTamp, md5OfStr, args, UserAccount);


            return result;
        }

        /// <summary>
        /// CRM查询物料接口
        /// </summary>
        public string CRMSearchMATERIAL(string code, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/getDataByPK/query_material";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";

            DataTable dt = APISetting("查询物料");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }

            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToSearchNews(requestUri1, systemid, currentTimeTamp, md5OfStr, code, UserAccount);


            return result;
        }

        /// <summary>
        /// CRM查询物料分组接口
        /// </summary>
        public string CRMSearchGroup(string code, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/getDataByPK/query_marerial_group";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";

            DataTable dt = APISetting("查询物料分组");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }

            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToSearchGroupNews(requestUri1, systemid, currentTimeTamp, md5OfStr, code, UserAccount);


            return result;
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }

        /// <summary>
        /// CRM查询物料POST
        /// </summary>
        public static string PostToSearchNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string code, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\""+UserAccount+"\"},\"mainTable\":{\"code\":\""+code+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            if (jo == null)
            {
                return "无结果";
            }
            else if (jo.ToString().Contains("status"))
            {
                string returnCode = jo["info"].ToString();
                return returnCode;
            }
            else if (jo["result"].ToString() == "{}")
            {
                return "无结果";
            }
            else
            {

                JToken rtToken = jo.SelectToken("result");
                JObject rt = (JObject)JsonConvert.DeserializeObject(rtToken.ToString());
                JToken mtToken = rt.SelectToken("mainTable");
                JObject mt = (JObject)JsonConvert.DeserializeObject(mtToken.ToString());
                string returnCode = mt["code"].ToString();
                return returnCode;
            }

        }

        /// <summary>
        /// CRM查询物料分组POST
        /// </summary>
        public static string PostToSearchGroupNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string code, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\""+UserAccount+"\"},\"mainTable\":{\"code\":\""+code+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            if (jo == null)
            {
                return "无结果";
            }
            else if (jo.ToString().Contains("status"))
            {
                string returnCode = jo["info"].ToString();
                return returnCode;
            }
            else if (jo["result"].ToString() == "{}")
            {
                return "无结果";
            }
            else
            {

                JToken rtToken = jo.SelectToken("result");
                JObject rt = (JObject)JsonConvert.DeserializeObject(rtToken.ToString());
                JToken mtToken = rt.SelectToken("mainTable");
                JObject mt = (JObject)JsonConvert.DeserializeObject(mtToken.ToString());
                string returnCode = mt["code"].ToString();
                return returnCode;
            }
        }

        /// <summary>
        /// CRM新增物料POST
        /// </summary>
        public static Return PostToPushNews(string url, string systemid, string currentTimeTamp, string md5OfStr, MaterialModel.materialList mainTable,string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\""+UserAccount+"\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value.Replace("%", "%25"));
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            //string[] sArray = result.Split(new string[] { "}}\",\"status\":\"", "}]" }, StringSplitOptions.None);
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            //if (resAry[resAry.Length - 1].IndexOf("1") > -1)
            //{
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            //}
            @return.status = status;
            @return.datajson = json;
            return @return;
        }
        /// <summary>
        /// CRM更新物料POST
        /// </summary>
        public static Return PostToUpdateNews(string url, string systemid, string currentTimeTamp, string md5OfStr, MaterialModel.materialList mainTable,string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\""+UserAccount+"\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value.Replace("%", "%25"));
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            result = Regex.Unescape(result);//去除转义符
            result = Regex.Unescape(result);//去除转义符
            //string[] sArray = result.Split(new string[] { "}}\",\"status\":\"", "}]" }, StringSplitOptions.None);
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            //if (resAry[resAry.Length - 1].IndexOf("1") > -1)
            //{
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            //}
            @return.status = status;
            @return.datajson = json;
            return @return;
        }


        /// <summary>
        /// CRM新增物料分组POST
        /// </summary>
        public static Return PostToPushGroupNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string[] args, string UserAccount)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                 {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\""+UserAccount+"\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":{\"code\":\""+args[0]+"\",\"ms\":\""+args[1]+"\",\"name\":\""+args[2]+"\",\"parent_category\":\""+args[3]+"\",\"erpfznm\":\""+args[4]+"\",\"erpffznm\":\""+args[5]+"\"}}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            string b = builder.ToString();
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            //string[] sArray = result.Split(new string[] { "}}\",\"status\":\"", "}]" }, StringSplitOptions.None);
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            //if (resAry[resAry.Length - 1].IndexOf("1") > -1)
            //{
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            //}
            @return.status = status;
            @return.datajson = json;
            return @return;
        }

        /// <summary>
        /// CRM更新物料分组POST
        /// </summary>
        public static Return PostToUpdateGroupNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string[] args, string UserAccount)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                 {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\""+UserAccount+"\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":{\"code\":\""+args[0]+"\",\"ms\":\""+args[1]+"\",\"name\":\""+args[2]+"\",\"parent_category\":\""+args[3]+"\",\"erpfznm\":\""+args[4]+"\",\"erpffznm\":\""+args[5]+"\"}}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            string b = builder.ToString();
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            result = Regex.Unescape(result);//去除转义符
            result = Regex.Unescape(result);//去除转义符
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            //}
            @return.status = status;
            @return.datajson = json;
            return @return;
        }

        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }


        /**
       * 接口返回值自定义 
       */
        public class Return
        {
            public string status { get; set; }
            public string[] datajson { get; set; }
        }
    }
}
